package com.demo.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

//配合c3p0连接池使用的工具类
public class C3P0Utiles {
    //私有化构造方法
    private C3P0Utiles() {
    }

    //创建c3p0连接池对象(全局统一）
    //配置文件名称为c3p0才能默认去读取配置文件的内容
    private static final ComboPooledDataSource source = new ComboPooledDataSource();

    //定义静态方法---注册驱动以及获取数据库连接
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        //获取连接（连接池默认注册数据库驱动）
        return source.getConnection();
    }

    //定义静态方法---关闭资源
    public static void close(Connection conn, Statement stat, ResultSet rs) {
        if (rs != null)
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
                rs = null;
            }
        if (stat != null)
            try {
                stat.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
                stat = null;
            }
        if (conn != null)
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
                conn = null;
            }
    }
}
